//
//  NewsInfoController.m
//  GuShiNews
//
//  Created by huachun on 2019/8/16.
//  Copyright © 2019 Jones. All rights reserved.
//

#import "NewsInfoController.h"
#import "NewsInfoBottomView.h"
#import "NewsInfoTopHeaderView.h"
#import "NewsModel.h"
#import "NewsInfoShowCell.h"
#import "PublicTopHeaderView.h"
#import "NewsCommentCell.h"
#import "HomeInputView.h"
#import "JoneCunChu.h"
#import "MementoCenter.h"
#import "NSObject+MementoCenter.h"
#import "UserJubuViewModel.h"
#import "RootSuperAction.h"
#import "CommentViewModel.h"
#import "GetCommentVModel.h"
#import "CommentModel.h"
#import "SuiJiViewModel.h"
#import "HomeNewsCell.h"
#import "NewsAction.h"

@interface NewsInfoController ()<UINavigationControllerDelegate,CommentDelegate,GetCommentDelegate,SuijiSideNewsDelegate>{
    BOOL Like_OK;
    NSInteger page;
    
    NSString *to_comment_id;
    NSString *to_userid;
}

@property (nonatomic, strong) NewsInfoBottomView *Bottom_view;
@property (nonatomic, strong) HomeInputView      *shuruView;

@property (nonatomic, strong) NSMutableArray     *Like_list;
@property (nonatomic, strong) NSMutableArray     *Look_list;

@property (nonatomic, strong) NSMutableArray     *SuiJi_list;

@property (nonatomic, strong) NSMutableArray     *Comment_list;

@end

@implementation NewsInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.TableView addGestureRecognizer:singleTapGesture];
    [self.view addSubview:self.TableView];
    self.TableView.frame=CGRectMake(0, 0, RECRWITCH, RECERHEIGHT-(NAV_Height-20));
    [self.TableView registerClass:[NewsInfoTopHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.TableView registerClass:[PublicTopHeaderView class] forHeaderFooterViewReuseIdentifier:@"publicheader"];
    
    _Comment_list = [NSMutableArray new];
    _SuiJi_list = [NSMutableArray new];
    
    __weak __typeof(&*self)weakSelf = self;
    _Bottom_view = [NewsInfoBottomView show:CGRectMake(0, RECERHEIGHT-(NAV_Height-20), RECRWITCH, NAV_Height-25)];
    _Bottom_view.SelectBlock = ^(NSInteger type) {
        if (type==0) {
            [weakSelf goback];
        }else if (type==1){
            
            if ([UserModel info].userid) {
                weakSelf.shuruView.textField.placeholder = @"请输入评论内容";
                [weakSelf.shuruView.textField becomeFirstResponder];
                
                self->to_comment_id = nil;
                self->to_userid = nil;
                
                if (weakSelf.Comment_list.count>0) {
                    [weakSelf.TableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                }else{
                    [weakSelf.TableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionBottom animated:YES];
                }
                
            }else{
                [RootSuperAction Actiontodone:JonesGOTO_Login view:self dictionary:@{}];
            }
            
        }else if (type==2){
            [weakSelf godoneLike];
        }else if (type==3){
            [weakSelf gotojubao];
        }
    };
    [self.view addSubview:_Bottom_view];
    if ([_Model.news_count intValue]>0) {
        [_Bottom_view setcommontcount:_Model.news_count];
    }
    
    _shuruView = [[HomeInputView alloc] initWithFrame:CGRectMake(0, RECERHEIGHT, RECRWITCH, 45)];
    _shuruView.selectblock = ^(NSString * _Nonnull title) {
        [weakSelf addcomment_net:title];
    };
    [self.view addSubview:_shuruView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillhideShow:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    Like_OK = NO;
    
    _Like_list = [NSMutableArray new];
    
    @try {
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LikeArray"]) {
            [shuju recoverFormStateWithKey:@"LikeArray"];
            _Like_list = shuju.JoneArray;
        }
        
        [_Like_list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NewsModel *linmodel = (NewsModel *)obj;
            if ([linmodel.news_id isEqualToString:weakSelf.Model.news_id]) {
                self->Like_OK = YES;
            }
        }];
        
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    [_Bottom_view setlike:Like_OK];
    
    [self cunlook];
    [self laodmore:NO];
    [self suijiLoad];
}

- (void)suijiLoad{
    SuiJiViewModel *viewmodel = [[SuiJiViewModel alloc] init:@{@"type":@"0"}];
    viewmodel.delegate =self;
}

- (void)SuijiSideNewsSucces:(int)value array:(NSMutableArray *)array page:(NSInteger)page{
    if (value==1) {
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NewsModel *modellin = obj;
            if (![modellin.news_id isEqualToString:_Model.news_id]) {
                [_SuiJi_list addObject:modellin];
            }
        }];
        [self.TableView reloadData];
    }
}

- (void)gotojubao{
    __weak __typeof(&*self)weakSelf = self;
    UserJubuViewModel *actionjubao = [UserJubuViewModel show:self dic:@{@"userid":@"0",@"type":@"0",@"to_userid":@"0",@"to_id":_Model.news_id}];
    actionjubao.selectblock = ^(BOOL type) {
        [weakSelf cunJubao];
    };
}

- (void)cunJubao{
    __weak __typeof(&*self)weakSelf = self;
    NSMutableArray *jubaolist = [NSMutableArray new];
    @try {
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"JubaoArray"]) {
            [shuju recoverFormStateWithKey:@"JubaoArray"];
            jubaolist = shuju.JoneArray;
        }
        [jubaolist enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NewsModel *linmodel = (NewsModel *)obj;
            if ([linmodel.news_id isEqualToString:weakSelf.Model.news_id]) {
                [jubaolist removeObjectAtIndex:idx];
                *stop = YES;
            }
        }];
        if (jubaolist.count>0) {
            [jubaolist insertObject:_Model atIndex:0];
        }else{
            [jubaolist addObject:_Model];
        }
        shuju.JoneArray=jubaolist;
        [shuju saveStateWithKey:@"JubaoArray"];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
}

- (void)cunlook{
    __weak __typeof(&*self)weakSelf = self;
    _Look_list = [NSMutableArray new];
    
    @try {
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"histryArray"]) {
            [shuju recoverFormStateWithKey:@"histryArray"];
            _Look_list = shuju.JoneArray;
        }
        [_Look_list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NewsModel *linmodel = (NewsModel *)obj;
            if ([linmodel.news_id isEqualToString:weakSelf.Model.news_id]) {
                [self->_Look_list removeObjectAtIndex:idx];
                *stop = YES;
            }
        }];
        if (_Look_list.count>0) {
            [_Look_list insertObject:_Model atIndex:0];
        }else{
            [_Look_list addObject:_Model];
        }
        shuju.JoneArray=_Look_list;
        [shuju saveStateWithKey:@"histryArray"];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
}


- (void)godoneLike{
    __weak __typeof(&*self)weakSelf = self;
    
    @try {
        if (Like_OK) {
            [_Like_list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NewsModel *linmodel = (NewsModel *)obj;
                if ([linmodel.news_id isEqualToString:weakSelf.Model.news_id]) {
                    [self->_Like_list removeObjectAtIndex:idx];
                    *stop = YES;
                }
            }];
            Like_OK = NO;
        }else{
            if (_Like_list.count>0) {
                [_Like_list insertObject:_Model atIndex:0];
            }else{
                [_Like_list addObject:_Model];
            }
            Like_OK = YES;
        }
        
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        shuju.JoneArray=_Like_list;
        [shuju saveStateWithKey:@"LikeArray"];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    [_Bottom_view setlike:Like_OK];
}

- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    [_shuruView.textField resignFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_shuruView.textField resignFirstResponder];
}

- (void)addcomment_net:(NSString *)title{
    [_shuruView.textField resignFirstResponder];
    
    NSMutableDictionary *postdic = [NSMutableDictionary new];
    [postdic setValue:[UserModel info].userid forKey:@"userid"];
    [postdic setValue:_Model.news_id forKey:@"news_id"];
    [postdic setValue:@"12" forKey:@"name"];
    [postdic setValue:to_comment_id?to_comment_id:@"" forKey:@"to_comment_id"];
    [postdic setValue:to_userid?to_userid:@"" forKey:@"to_userid"];
    [postdic setValue:title forKey:@"comment"];

    CommentViewModel *viewmodel = [[CommentViewModel alloc] init:postdic];
    viewmodel.delegate=self;
}

-(void)CommentSucces:(int)value dic:(NSDictionary *)dic{
    if (value==1) {
        _shuruView.textField.text = nil;
        [self laodmore:NO];
        
        to_comment_id = nil;
        to_userid = nil;
        
        _Model.news_count = [NSString stringWithFormat:@"%i",[_Model.news_count intValue] +1];
        [self.TableView reloadData];
        [_Bottom_view setcommontcount:_Model.news_count];
    }
}

- (void)laodmore:(BOOL)more{
    NSMutableDictionary *postdic = [NSMutableDictionary new];
//    if (more) {
////        CommentModel *linmodel = [_Comment_list lastObject];
////        page = [linmodel.comment_id integerValue];
//    }else{
//        page = 0;
//        [self.TableView reloadData];
//    }
    [postdic setValue:@"" forKey:@"userid"];
    [postdic setValue:_Model.news_id forKey:@"news_id"];
    [postdic setValue:[NSString stringWithFormat:@"%li",(long)page] forKey:@"page"];
    GetCommentVModel *getcomment = [[GetCommentVModel alloc] init:postdic];
    getcomment.delegate=self;
}

-(void)GetCommentSucces:(int)value array:(NSMutableArray *)array page:(NSInteger)page{
    [self.TableView.mj_footer endRefreshing];
    if (value==1) {
        if (page==0) {
            [_Comment_list removeAllObjects];
            page = 0;
        }
        if (array.count<20) {
            self.TableView.mj_footer.hidden = YES;
        }
        [_Comment_list addObjectsFromArray:array];
        [self.TableView reloadData];
    }else{

    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillhideShow:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)keyboardWillhideShow:(NSNotification *)aNotification{
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self->_shuruView.frame=CGRectMake(0, RECERHEIGHT, RECRWITCH, 45);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)keyboardWillShow:(NSNotification *)aNotification{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self->_shuruView.frame=CGRectMake(0, RECERHEIGHT-keyboardRect.size.height-45, RECRWITCH, 45);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }
    else if (section==1){
        return _SuiJi_list.count;
    }
    else{
        return _Comment_list.count;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        NewsInfoTopHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
        view.Model = _Model;
        return view;
    }
    else if(section==1){
        PublicTopHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"publicheader"];
        view.Tittle.text=@"热门";
        return view;
    }
    else{
        PublicTopHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"publicheader"];
        view.Tittle.text=@"评论";
        if ([_Model.news_count intValue]>0) {
            view.Tittle.text=[NSString stringWithFormat:@"评论(%@)",_Model.news_count];
        }
        return view;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        if (_Model.news_show_type==0) {
            return _Model.title_height + 85;
        }
        return _Model.title_height + 100 + (RECRWITCH-50)/3*2;
    }
    else if (section==1){
        return 60;
    }
    else{
        return 60;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return _Model.info_height+20;
    }
    else if (indexPath.section==1){
        NewsModel *model = [self.SuiJi_list objectAtIndex:indexPath.row];
        return model.news_height;
    }
    else{
        CommentModel *model = [_Comment_list objectAtIndex:indexPath.row];
        if ([model.to_comment_id intValue]>0) {
            return 85 + model.comment_height + model.to_comment_height;
        }else{
            return 85 + model.comment_height;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak __typeof(&*self)weakSelf = self;
    if (indexPath.section==0) {
        NewsInfoShowCell *cell = [NewsInfoShowCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
        cell.Model            = _Model;
        return cell;
    }
    else if (indexPath.section==1){
        HomeNewsCell *cell = [HomeNewsCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
        cell.Model = [self.SuiJi_list objectAtIndex:indexPath.row];
        return cell;
    }
    else{
        CommentModel *model = [_Comment_list objectAtIndex:indexPath.row];
        NewsCommentCell *cell = [NewsCommentCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
        cell.Model = model;
        cell.SuperVC = self;
        cell.seleckblock = ^(NSInteger type) {
            if (type==0) {
                [self->_Comment_list removeObjectAtIndex:indexPath.row];
                [self.TableView reloadData];
            }else{
                weakSelf.shuruView.textField.placeholder = [NSString stringWithFormat:@"@%@//",model.name];
                [weakSelf.shuruView.textField becomeFirstResponder];
                
                self->to_comment_id = model.comment_id;
                self->to_userid = model.userid;
            }
        };
        return cell;
    }
}


- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated{
    if(viewController == self){
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }else{
        [self.navigationController setNavigationBarHidden:NO animated:animated];
        if(self.navigationController.delegate == self){
            self.navigationController.delegate = nil;
        }
    }
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        NewsModel *model = [self.SuiJi_list objectAtIndex:indexPath.row];
        [NewsAction Actiontodone:JonesGOTO_NewsInfo view:self dictionary:@{@"model":model}];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}


@end
